import os
from flask import current_app
from models.models import Recording, Sentence, db

class RecordingController:
    @staticmethod
    def get_user_recordings(user_id):
        recordings = Recording.query.filter_by(user_id=user_id).all()
        return {
            'code': 200,
            'message': '获取成功',
            'data': [recording.to_dict() for recording in recordings]
        }
    
    @staticmethod
    def get_user_stats(user_id):
        # Count completed recordings
        completed = Recording.query.filter_by(user_id=user_id).count()
        
        # Count total sentences
        total = Sentence.query.count()
        
        # Calculate remaining
        remaining = total - completed
        
        return {
            'code': 200,
            'message': '获取成功',
            'data': {
                'completed': completed,
                'remaining': remaining
            }
        }
    
    @staticmethod
    def upload_recording(user_id, sentence_id, audio_file):
        # Check if sentence exists
        sentence = Sentence.query.get(sentence_id)
        if not sentence:
            return {'code': 404, 'message': '句子不存在', 'data': None}
        
        # Check if user already recorded this sentence
        existing_recording = Recording.query.filter_by(
            user_id=user_id,
            sentence_id=sentence_id
        ).first()
        
        if existing_recording:
            # Delete the old recording file if it exists
            try:
                old_file_path = os.path.join(current_app.config['UPLOAD_FOLDER'], 
                                           os.path.basename(existing_recording.audio_file))
                if os.path.exists(old_file_path):
                    os.remove(old_file_path)
            except Exception as e:
                # Log the error but continue
                print(f"Error removing old file: {e}")
        
        # Generate filename
        filename = f"user_{user_id}_sentence_{sentence_id}.wav"
        filepath = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)
        
        # Save the file
        audio_file.save(filepath)
        
        # Create or update recording record
        if existing_recording:
            existing_recording.audio_file = f"/storage/recordings/{filename}"
            recording = existing_recording
        else:
            recording = Recording(
                user_id=user_id,
                sentence_id=sentence_id,
                audio_file=f"/storage/recordings/{filename}"
            )
            db.session.add(recording)
        
        db.session.commit()
        
        return {
            'code': 200,
            'message': '上传成功',
            'data': recording.to_dict()
        }
    
    @staticmethod
    def get_audio_file(recording_id):
        recording = Recording.query.get(recording_id)
        
        if not recording:
            return None
        
        # Extract filename from the audio_file path
        filename = os.path.basename(recording.audio_file)
        file_path = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)
        
        if not os.path.exists(file_path):
            return None
            
        return file_path 